<template>
  <div class="app-container">
    <Search :paramsList="paramsList" :searchParams="searchParams" @search="handleSearch"/>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd()">新增
        </el-button>
      </el-col>
    </el-row>
    <Table ref="table" :loading="loading" :headerData="headerData" :tableData="tableData" @selection-change="handleSelectionChange">
      <template slot="operation" slot-scope="scope">
        <el-button type="text" @click="handleEdit(scope.row)" :disabled="!hasEditPermission">编辑</el-button>
        <el-button type="text" @click="handleDelete(scope.row)" :disabled="!hasDeletePermission">删除</el-button>
        <el-button type="text" @click="handleDelete(scope.row)" :disabled="!hasDeletePermission">下架</el-button>
      </template>
    </Table>

    <!-- 分页组件 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryParams.pageNum"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="queryParams.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      class="pagination-container">
    </el-pagination>
  </div>
</template>


<script>

import Search from "@/components/Select/index.vue";
import Table from "@/components/Tables/index.vue";
import { getArticleList,remove } from "@/api/business/article";

export default {
  components: {Table, Search},
  data(){
    return{
      paramsList:[
        {label: "标题", type: "input", key: "articleTitle"},
        {label: "创建日期", type: "date", key: "createTimeRange"},
      ],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        articleTitle: undefined,
        beginTime: undefined,
        endTime: undefined
      },
      searchParams: {},
      loading: false,
      tableData: [],
      total: 0,
      headerData: [
        {prop: 'articleTitle', label: '标题'},
        {prop: 'sort', label: '排序', width: '80'},
        {prop: 'status', label: '状态', computed: { '0': '已下架', '1': '已上架', 0: '已下架', 1: '已上架' }},
        {prop: 'createTime', label: '创建时间'},
        {type: 'operation', label: '操作', width: '150'}
      ],
      // 多选相关
      multipleSelection: [],
      // 权限控制（按需接入权限指令）
      hasEditPermission: true,
      hasDeletePermission: true,
    }
  },
  methods: {
    // 处理查询（来自搜索组件）
    handleSearch(params) {
      this.handleSearchParams(params)
      this.getList()
    },

    // 解析搜索参数到 queryParams
    handleSearchParams(params) {
      this.queryParams.articleTitle = undefined
      this.queryParams.beginTime = undefined
      this.queryParams.endTime = undefined

      if (params.articleTitle) {
        this.queryParams.articleTitle = params.articleTitle.trim()
      }
      if (params.createTimeRange) {
        if (Array.isArray(params.createTimeRange) && params.createTimeRange.length === 2) {
          this.queryParams.beginTime = params.createTimeRange[0]
          this.queryParams.endTime = params.createTimeRange[1]
        } else if (typeof params.createTimeRange === 'string' && params.createTimeRange.includes('-')) {
          const dates = params.createTimeRange.split('-')
          if (dates.length >= 4) {
            this.queryParams.beginTime = `${dates[0]}-${dates[1]}-${dates[2]}`
            this.queryParams.endTime = `${dates[3]}-${dates[4]}-${dates[5]}`
          }
        }
      }
    },

    // 分页大小变化
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getList()
    },

    // 当前页变化
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.getList()
    },

    // 列表数据
    getList() {
      this.tableData = []
      this.loading = true

      const requestParams = {}
      Object.keys(this.queryParams).forEach(key => {
        if (this.queryParams[key] !== undefined && this.queryParams[key] !== null && this.queryParams[key] !== '') {
          requestParams[key] = this.queryParams[key]
        }
      })

      getArticleList(requestParams).then(res => {
        if (res && (res.code === 200 || res.code === 0)) {
          this.tableData = res.rows || res.data || []
          this.total = res.total || (res.data && res.data.total) || 0
        } else {
          this.$message.error(res && res.msg ? res.msg : '获取文章列表失败')
        }
      }).catch(err => {
        console.error('获取文章列表错误:', err)
        this.$message.error('获取文章列表失败')
      }).finally(() => {
        this.loading = false
      })
    },

    // 新增
    handleAdd() {
      this.$message.info('请在此实现新增文章逻辑')
    },

    // 编辑
    handleEdit(row) {
      if (!this.hasEditPermission) return
      console.log('编辑文章:', row)
      this.$message.info('请在此实现编辑文章逻辑')
    },

    // 删除
    handleDelete(row) {
      if (!this.hasDeletePermission) return
      console.log('删除文章:', row)
      this.$confirm('确认删除该文章吗？', '提示', { type: 'warning' })
        .then(() => {
          remove({dataIdList:[row.id]}).then(res=>{
            if (res.code === 200){
              this.$message.success(res.msg)
            }else {
              this.$message.error(res.msg)
            }
          })
        })
        .catch(() => {})
    },

    // 多选变化
    handleSelectionChange(val) {
      this.multipleSelection = val
    }
  }
}
</script>

<style scoped lang="scss">

</style>
